package com.codingman.data.mybatis.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.CollectionUtils;

public class UpdateSqlProvider extends BaseSqlProviderSupport implements ProviderMethodResolver {
	public <S> String update(S entity) {
		Class<?> entityClass = entity.getClass();
		TableInfo table = TableInfo.forClass(entityClass);
		return new SQL().UPDATE(table.getName())
				.SET(this.getColumns(table))
				.WHERE(table.getPKConlumn() + " = #{" + table.getPKConlumn() + "}")
				.toString();
	}

	private String[] getColumns(TableInfo table) {
		Collection<String> columns = table.getColumns();
		if (CollectionUtils.isEmpty(columns)) {
			return new String[0];
		}
		List<String> results = new ArrayList<String>();
		for(String column : columns) {
			
			if(column.equals(table.getPKConlumn())) {
				continue;
			}
			results.add(column + " = #{" + column + "}");
		}
		return results.toArray(new String[0]);
	}
}
